import React, { Component } from 'react';
import {
  View, Text, StyleSheet, TouchableOpacity, Image, TextInput, ScrollView,
  Alert, Keyboard
} from 'react-native';
import ImagePicker from 'react-native-image-picker';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import ValidateDataUtil from '../../../utils/ValidateDataUtil';
import StorageHelper from '../../../utils/storageHelper';
import Upload from '../../../utils/Upload';
import { STORAGE_CONSTANT } from '../../../config/storage';
import { GLOBAL } from '../../../config/global';
import ModalPicDelComponent from '../../../component/ModalPicDelComponent';
import { enterpriseStyles } from '../_common/enterpriseStyle';
import { Common } from '../../../component/common/Common';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';

const scale = GLOBAL.SCALE;
const arrowLeft = require('../../../imgs/arrow-left.png');
const uploadPic = require('../../../imgs/store/upload.png');

const modalPicDelCfg = {
  visible: false,
  uri: null,
  delPress: () => { },
  picPress: () => { }
}
const attachmentObj = {
  index: null,
  type: null
}
let addressCodeParam = null;
let responseDataParams = {};

export class EnterpriseCreateAdditionInfo extends Component {

  static navigationOptions = ({ navigation }) => {
    const params = navigation.state.params || {};
    const { setBank, bankList, setAddress, addressList, contactData, setEditInfo,
      setContactObjList, invoiceData, setInvoice, addressObj, responseData } = params;

    responseDataParams = responseData || {};
    if (responseDataParams) {
      responseDataParams.step = 2;
    }

    if (addressObj) {
      addressCodeParam = addressObj;
    }
    if (responseData) {
      if (setEditInfo) {
        setEditInfo(
          responseData.companyInfoVO
        );
      }
    }
    //生成银行信息 
    if (setBank) {
      if (bankList) {
        setBank(bankList);
      } else if (responseData.acctList && responseData.acctList.length > 0) {
        setBank(responseData);
      }
    }

    if (setAddress) {
      if (addressList) {
        setAddress(addressList);
      } else if (responseData.addressList && responseData.addressList.length > 0) {
        setAddress(responseData);
      }
    }

    //生成联系人信息
    if (setContactObjList) {
      if (contactData) {
        setContactObjList(contactData);
      } else if (responseData.contactorList && responseData.contactorList.length > 0) {
        setContactObjList(responseData.contactorList);
      }
    }

    //生成开票信息
    if (setInvoice) {
      if (invoiceData) {
        setInvoice(invoiceData);
      } else if (responseData.companyInfoVO) {
        setInvoice(responseData.companyInfoVO);
      }
    }
    return {
      header: null,
      gesturesEnabled: false
    };
  };

  requesting;
  constructor(props) {
    super(props);

    this.state = {
      previewModalVisible: false,
      contactSourceList: [],
      contactObjList: [],
      invoiceSource: null,
      invoice: {},
      referenceStr: '请选择',
      loaded: false,
      addressList: [],
      bankList: [],
      comments: '',
      recvInvoiceAddress: '',
      offsetY: 0
    }
    this.choice = props.navigation.state.params.choice || {};
    this.contactDirty = false;
    this.invoiceDirty = false;

    this.sendData = responseDataParams;
    this.sendData.step = 2;
    if (responseDataParams.companyInfoVO) {
      this.companyId = responseDataParams.companyInfoVO.companyId;
    }

    this.selectPhotoTapped = this.selectPhotoTapped.bind(this);
    this.invoiceHandle = this.invoiceHandle.bind(this);
    this.setContactObjList = this.setContactObjList.bind(this);
    this.setInvoice = this.setInvoice.bind(this);
    this.setAddress = this.setAddress.bind(this);
    this.setBank = this.setBank.bind(this);
    this.setEditInfo = this.setEditInfo.bind(this);

    this.requireQualification = this.props.navigation.state.params.requireQualification;
    modalPicDelCfg.picPress = () => {
      modalPicDelCfg.visible = false;
      modalPicDelCfg.uri = null;
      this.setState({
        previewModalVisible: false,
      });
    }

    modalPicDelCfg.delPress = () => {
      modalPicDelCfg.visible = false;
      modalPicDelCfg.uri = null;
      const { contactSourceList, contactObjList, delContactorId } = this.state;
      const { index, type } = attachmentObj;
      let delItem;
      let delType;
      if (type == 'contact') {
        if (responseDataParams.contactorList && responseDataParams.contactorList.length > 0) {
          responseDataParams.contactorList.map((item, i) => {
            if (item.contactorFileId === delContactorId) {
              delItem = item;
              delType = true;
            }
          })
        }
        this._delItem({ item: delItem, delType, index });

      } else if (type == 'invoice') {
        this.setState({
          invoiceSource: null,
          invoice: {},
          previewModalVisible: false,
        });
      }
    }

    this._keyboardDidShow = this._keyboardDidShow.bind(this);
    this._keyboardDidHide = this._keyboardDidHide.bind(this);
    this._getAddressRowViews = this._getAddressRowViews.bind(this);
    this._getBankRowViews = this._getBankRowViews.bind(this);
    this._getInvoiceView = this._getInvoiceView.bind(this);

    this.addressList = [];
    this.bankList = [];
    this.userIdsChecked = {};

    this.creditCode = this.props.navigation.state.params.creditCode;
  }

  async _delItem (data) {
    const { contactSourceList, contactObjList } = this.state;

    if (data.delType) {
      const params = {};
      params.companyContactor = data.item; //companyContactor
      params.bizType = 'COMPANY_CONTACT_INFO'; //COMPANY_CONTACT_INFO
      const delResponse = await HTTP.POST(API_GENERATE(API.DELETE_COMPANY_INFO), params);
      if (delResponse) {
        console.log('del suc')
      } else {
        console.log('del fal')
      }
    }

    contactObjList.splice((contactSourceList.length == contactObjList.length) ? data.index : data.index + 1, 1);
    contactSourceList.splice(data.index, 1);
    this.setState({
      contactSourceList,
      contactObjList,
      previewModalVisible: false,
    });
  }

  setInvoiceObjImgs (invoiceFileId) {
    //图片预览
    if (invoiceFileId) {
      this.loadedImgs(invoiceFileId);
    }
  }

  async loadedImgs (invoiceFileId) {
    const { invoiceSource } = this.state;
    this.setState({
      invoiceSource: null
    })

    this.setState({
      loaded: true
    });

    const imgs = await HTTP.GET(API_GENERATE(API.GET_IMG_VIEW), { fileId: invoiceFileId }, {
      rejectError: false,
      handleError: true,
    }, 30000);

    this.setState({
      loaded: false
    });
    if (imgs && imgs.image) {
      let { image } = imgs;
      if (image) {
        this.setState({
          invoiceSource: { uri: image, fileId: invoiceFileId }
        })
      }
    }
  }

  setContactObjList (contact) {
    const { contactSourceList } = this.state;
    if (contact.index >= 0) {
      const { index } = contact;
      const { contactObjList } = this.state;
      if (contactObjList[index]) {
        delete contact.default;
        contactObjList[index] = contact;
        contactObjList[index].companyId = this.companyId;
        contactObjList[index].id = contact.id ? contact.id : null;
        this.setState({
          contactObjList
        });
        this.contactDirty = true;
      } else {
        contactObjList[0] = contact;
        contactObjList[0].companyId = this.companyId;
        contactObjList[0].id = contact.id ? contact.id : null;
        this.setState({
          contactObjList
        });
      }
      this.sendData.contactorList = this.state.contactObjList;
    } else {
      for (let i = 0; i < contact.length; i++) {
        contact[i].index = i;
      }
      this.sendData.contactorList = contact;
      this.setState({
        contactObjList: contact
      });
    }
  }

  setInvoice (invoice) {
    const { taxCode, openBankName, openAcctNo, invoicePhoneNo, invoiceAddress } = invoice;
    this.sendData.companyInfoVO.openBankName = openBankName;
    this.sendData.companyInfoVO.openAcctNo = openAcctNo;
    this.sendData.companyInfoVO.taxCode = taxCode;
    this.sendData.companyInfoVO.invoicePhoneNo = invoicePhoneNo;
    this.sendData.companyInfoVO.invoiceAddress = invoiceAddress;
    this.setState({
      invoice
    });
  }

  setBank (bankList) {
    let newArr = bankList;
    if (bankList && bankList.length) {
      newArr = Array.from(new Set(bankList));
    }
    if (newArr && newArr.length) {
      if (newArr.length > 1) {
        this.bankList = newArr;
      }
      else if (this.bankList && this.bankList.length) {
        this.bankList = newArr;
      }
      else {
        this.bankList.push(newArr[0]);
      }
      const banks = this.bankList.filter((bank) => {
        if (bank) {
          return bank.checked;
        }
      });

      this.sendData.acctList = banks.map((banks) => {
        banks.companyId = this.companyId;
        return banks;
      });

      this.setState({
        bankList: banks,
      });
    } else {
      if (newArr.acctList && newArr.acctList.length > 1) {
        this.bankList = newArr.acctList;
      }
      else if (newArr.acctList && this.bankList && this.bankList.length) {
        this.bankList = newArr.acctList;
      }
      else if (newArr.acctList) {
        this.bankList.push(newArr.acctList[0]);
      } else {
        this.bankList = [];
      }
      this.setState({
        bankList: this.bankList
      });
      this.sendData.acctList = this.state.bankList;
    }
  }

  setAddress (addressList) {
    let newArr = addressList;
    if (newArr && newArr.length) {
      if (newArr.length > 1) {
        this.addressList = newArr;
      }
      else if (this.addressList.length) {
        this.addressList = newArr
      }
      else {
        this.addressList.push(newArr[0]);
      }

      const addresses = this.addressList.filter((address) => {
        return address.checked;
      });
      this.sendData.addressList = addresses.map((address) => {
        address.companyId = this.companyId;
        return address;
      });

      this.setState({
        addressList: addresses
      });
    } else {
      if (newArr.addressList && newArr.addressList.length > 1) {
        this.addressList = newArr.addressList;
      }
      else if (newArr.addressList && this.addressList && this.addressList.length) {
        this.addressList = newArr.addressList;
      }
      else if (newArr.addressList) {
        this.addressList.push(newArr.addressList[0]);
      } else {
        this.addressList = [];
      }
      this.setState({
        addressList: this.addressList
      });
      this.sendData.addressList = this.state.addressList;
    }
  }

  setEditInfo (baseInfo) {
    const { comments, recvInvoiceAddress } = baseInfo;
    this.sendData.companyInfoVO.comments = comments;
    this.sendData.companyInfoVO.recvInvoiceAddress = recvInvoiceAddress;
    this.setState({
      comments,
      recvInvoiceAddress
    });
  }

  async componentWillMount () {
    this.props.navigation.setParams({
      setContactObjList: this.setContactObjList,
      setInvoice: this.setInvoice,
      setAddress: this.setAddress,
      setBank: this.setBank,
      setEditInfo: this.setEditInfo,
    });
    //获取示例图片
    this.getImgDemo();

    if (responseDataParams.contactorList) {
      this.setInvoiceObjImgs(responseDataParams.companyInfoVO.invoiceFileId);
    }

    const dataDictionaryStr = await StorageHelper.get(STORAGE_CONSTANT.DICTIONARY);
    const dataDictionary = dataDictionaryStr ? JSON.parse(dataDictionaryStr) : {};

    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
  }

  async getImgDemo () {
    const imgDemo = await HTTP.GET(API_GENERATE(API.GET_IMG_DEMO));
    if (imgDemo) {
      this.setState({
        imgDemo
      })
    }
  }

  _getBankRowViews () {
    const { bankList } = this.state;
    const { responseData } = this.props.navigation.state.params;

    if (bankList && bankList.length > 0) {
      return (
        bankList.map((bank, index) => {
          const { openBankName, openAcctNo } = bank;
          return (
            <TouchableOpacity key={index} activeOpacity={.5} style={enterpriseStyles.optionView} onPress={() => {
              const { navigate } = this.props.navigation;
              navigate('BankArrayPage', {
                bankList: this.bankList,
                responseData
              });
            }}>
              <Text style={enterpriseStyles.text}>{`${openBankName}、${openAcctNo}`}</Text>
              <Image source={arrowLeft} style={enterpriseStyles.arrowLeft} />
            </TouchableOpacity>)
        })
      )
    } else {
      if (this.bankList && this.bankList.length > 0) {
        return (
          <TouchableOpacity activeOpacity={.5} style={enterpriseStyles.optionView} onPress={() => {
            const { navigate } = this.props.navigation;
            navigate('BankArrayPage', {
              bankList: this.bankList,
              responseData
            });
          }}>
            <Text style={enterpriseStyles.text}>请选择</Text>
            <Image source={arrowLeft} style={enterpriseStyles.arrowLeft} />
          </TouchableOpacity>
        )
      }
      else {
        return (
          <TouchableOpacity activeOpacity={.5} style={enterpriseStyles.optionView} onPress={() => {
            const { navigate } = this.props.navigation;
            navigate('BankAddPage', {
              goBack: 'EnterpriseCreateAdditionInfo',
              companyAcct: {},
            });
          }}>
            <Text style={enterpriseStyles.text}>请选择</Text>
            <Image source={arrowLeft} style={enterpriseStyles.arrowLeft} />
          </TouchableOpacity>
        )
      }
    }
  }

  _getAddressRowViews () {
    const { addressList } = this.state;
    const { responseData } = this.props.navigation.state.params;

    if (addressList && addressList.length > 0) {
      return (
        addressList.map((address, index) => {
          const { areaText, detailAddress, provinceCode, provinceName, cityCode, cityName, areaCode, areaName, addressName } = address;
          return (
            <TouchableOpacity key={index} activeOpacity={.5} style={enterpriseStyles.optionView} onPress={() => {
              const { navigate } = this.props.navigation;
              navigate('AddressArrayPage', {
                addressList: this.addressList,
                addressInfo: this.addressInfo,
                responseData
              });
            }}>
              <Text style={enterpriseStyles.text}>{`${areaText ? areaText : (provinceCode ? provinceName : '' + cityCode ? cityName : '' + areaCode ? areaName : '')} ${addressName || detailAddress}`}</Text>
              <Image source={arrowLeft} style={enterpriseStyles.arrowLeft} />
            </TouchableOpacity>)
        })
      )
    } else {
      if (this.addressList && this.addressList.length > 0) {
        return (
          <TouchableOpacity activeOpacity={.5} style={enterpriseStyles.optionView} onPress={() => {
            const { navigate } = this.props.navigation;
            navigate('AddressArrayPage', {
              addressList: this.addressList,
              addressInfo: this.addressInfo,
              responseData
            });
          }}>
            <Text style={enterpriseStyles.text}>请选择</Text>
            <Image source={arrowLeft} style={enterpriseStyles.arrowLeft} />
          </TouchableOpacity>
        )
      }
      else {
        return (
          <TouchableOpacity activeOpacity={.5} style={enterpriseStyles.optionView} onPress={() => {
            const { navigate } = this.props.navigation;
            navigate('AddressAddPage', {
              goBack: 'EnterpriseCreateAdditionInfo',
              companyAddress: {},
              addressInfo: this.addressInfo,
              areaText: ''
            });
          }}>
            <Text style={enterpriseStyles.text}>请选择</Text>
            <Image source={arrowLeft} style={enterpriseStyles.arrowLeft} />
          </TouchableOpacity>
        )
      }

    }

  }

  render () {
    const { loaded, keyboard } = this.state;
    const { corpTypeList } = this.props.navigation.state.params;
    let bankLabel = this.sendData.companyInfoVO.countryCode === '86' ? '必填' : '选填';

    //根据第一步选择的企业类型判断银行信息是否必填：供应商必填
    this.bankIfRequired = corpTypeList.filter((item) => {
      return item.corpType === '1';
    })
    //根据第一步选择的企业类型判断收发票地址是否必填：客户必填
    this.invoiceAddrIfRequired = corpTypeList.filter((item) => {
      return item.corpType === '2';
    })

    return (
      <ScrollView style={styles.scrollView} onScroll={(e) => {
        let offsetY = e.nativeEvent.contentOffset.y; //滑动距离
        this.setState({
          offsetY
        })
      }}>
        <View style={styles.container}>
          <ModalPicDelComponent {...modalPicDelCfg} />
          <View style={[styles.wrap, { top: keyboard ? -180 : 0 }]}>
            <Common type="headLeft" onPress={() => {
              const { navigate } = this.props.navigation;
              navigate('EnterpriseCreateBaseInfo', {
                responseData: this.sendData
              });
            }} ifHiddenTitle={true} imgStyle={{ marginLeft: 0, marginTop: GLOBAL.IS_IPHONEX ? 42 * scale : 18 * scale }} />
            <Text style={enterpriseStyles.titleText}>企业信息</Text>

            <View style={enterpriseStyles.field}>
              <Text style={enterpriseStyles.lableText}>联系人信息(必填)</Text>
              {this._getContactView()}
            </View>

            <View style={enterpriseStyles.field}>
              <View style={{ marginTop: 10 * scale }}>
                <Text style={[enterpriseStyles.lableText]}>收发货地址(选填)</Text>
              </View>
              {this._getAddressRowViews()}
            </View>

            <Text style={enterpriseStyles.lableText}>上传开票图片(支持jpg、png等图片格式，{bankLabel})</Text>
            <View style={enterpriseStyles.attachmentRow}>
              {this._getInvoiceView()}
            </View>
            {
              this.invoiceAddrIfRequired && this.invoiceAddrIfRequired.length ?
                <View style={enterpriseStyles.field}>
                  <Text style={enterpriseStyles.lableText}>发票邮寄地址(必填)</Text>
                  <TextInput
                    ref="invoiceInput"
                    style={enterpriseStyles.textInput}
                    underlineColorAndroid='transparent'
                    returnKeyType='done'
                    keyboardType='default'
                    placeholder={"请输入"}
                    placeholderTextColor="#404040"
                    maxLength={100}
                    editable={true}
                    defaultValue={this.state.recvInvoiceAddress}
                    onChangeText={(txt) => {
                      this.sendData.companyInfoVO.recvInvoiceAddress = txt;
                      // this.setState({
                      //     recvInvoiceAddress: txt
                      // })
                    }}
                    onFocus={(txt) => {
                      this.setState({
                        keyboard: true
                      })
                    }}
                    onBlur={(txt) => {
                      this.setState({
                        keyboard: false
                      })
                    }}
                  />
                </View>
                : null
            }
            <View style={enterpriseStyles.field}>
              <Text style={enterpriseStyles.lableText}>结算银行信息
                            {this.bankIfRequired && this.bankIfRequired.length ? '（必填）' : '（选填）'}</Text>
              {this._getBankRowViews()}
            </View>

            <View style={enterpriseStyles.field}>
              <Text style={enterpriseStyles.lableText}>备注</Text>
              <TextInput
                ref="bonusInput"
                style={enterpriseStyles.textInput}
                underlineColorAndroid='transparent'
                returnKeyType='done'
                keyboardType='default'
                placeholder={"请输入备注"}
                placeholderTextColor="#404040"
                maxLength={100}
                editable={true}
                defaultValue={this.state.comments}
                onChangeText={(txt) => {
                  this.sendData.companyInfoVO.comments = txt;
                }}
                onFocus={(txt) => {
                  this.setState({
                    keyboard: true
                  })
                }}
                onBlur={(txt) => {
                  this.setState({
                    keyboard: false
                  })
                }}
              />
            </View>

            <View style={enterpriseStyles.footBtnCell}>
              <TouchableOpacity style={enterpriseStyles.footBtn} onPress={() => {
                const { navigate } = this.props.navigation;
                this.sendData.addressList = this.addressList;
                this.sendData.acctList = this.bankList;
                navigate('EnterpriseCreateBaseInfo', {
                  responseData: this.sendData
                });
              }} activeOpacity={0.5} >
                <Text style={enterpriseStyles.footBtnText}>上一步</Text>
              </TouchableOpacity>
              <TouchableOpacity style={enterpriseStyles.footBtn} onPress={this._didPressNextBtn.bind(this)} activeOpacity={0.5} >
                <Text style={enterpriseStyles.footBtnText}>下一步</Text>
              </TouchableOpacity>
            </View>

          </View>
        </View>
        {
          this.state.loaded ?
            <View style={{ position: 'absolute', height: GLOBAL.SCREEN_HEIGHT, width: GLOBAL.SCREEN_WIDTH, top: this.state.offsetY }}>
              <PageStatusIndex status='loading' />
            </View>
            : null
        }

      </ScrollView>);

  }

  //渲染联系人信息
  _getContactView () {
    const { contactObjList } = this.state;
    this.contractType=[
			'不带入','姓名+邮箱','姓名+手机号'
    ]
    const contactRowViews = (contactObjList && contactObjList.length) ? contactObjList.map((item, i) => {
      item.index = i;
      let { mobileNo, contactorName, email,contactorDepart, contactorAddress,attachedFlag } = item;

      contactorName = contactorName || '请填写';
      mobileNo = mobileNo ? '、' + mobileNo : '';
      email=email ? '、' + email : '';
      contactorDepart = contactorDepart ? '、' + contactorDepart : '';
      contactorAddress = contactorAddress ? '、' + contactorAddress : '';
      attachedFlag = attachedFlag?'、' + this.contractType[attachedFlag-1]:'';
      const text = `${contactorName}${mobileNo}${email}${contactorDepart}${contactorAddress}${attachedFlag}`;

      return (
        <TouchableOpacity key={item.index} activeOpacity={.5} style={enterpriseStyles.optionView} onPress={() => {
          const { navigate } = this.props.navigation;
          navigate('ContactEditPage', {
            vo: item,
            addressCodeParam,
            countryCode: this.sendData.companyInfoVO.countryCode
          });
        }}>
          <Text style={enterpriseStyles.text}>{text}</Text>
          <Image source={arrowLeft} style={enterpriseStyles.arrowLeft} />
        </TouchableOpacity>
      );
    }) : (
        <TouchableOpacity key={0} activeOpacity={.5} style={enterpriseStyles.optionView} onPress={() => {
          const { navigate } = this.props.navigation;
          navigate('ContactEditPage', {
            vo: {
              index: 0,
              mobileNo: '',
            },
            addressCodeParam,
            countryCode: this.sendData.companyInfoVO.countryCode
          });
        }}>
          <Text style={enterpriseStyles.text}>请输入</Text>
          <Image source={arrowLeft} style={enterpriseStyles.arrowLeft} />
        </TouchableOpacity>
      );

    return contactRowViews;
  }

  //渲染开票信息
  _getInvoiceView () {
    const { invoice, invoiceSource, imgDemo } = this.state;
    let { taxCode, openBankName, openAcctNo, invoicePhoneNo, invoiceAddress } = invoice;
    let bankLabel = this.sendData.companyInfoVO.countryCode === '86' ? '必填' : '选填';
    taxCode = taxCode || '';
    openBankName = openBankName ? '、' + openBankName : '';
    openAcctNo = openAcctNo ? '、' + openAcctNo : '';
    invoicePhoneNo = invoicePhoneNo ? '、' + invoicePhoneNo : '';
    invoiceAddress = invoiceAddress ? '、' + invoiceAddress : '';
    const text = `${taxCode}${openBankName}${openAcctNo}${invoicePhoneNo}${invoiceAddress}`;

    const demoSource = imgDemo ? { uri: imgDemo } : require('../../../imgs/customer/invioceDemo.jpg');
    //发票图片
    const uploadCell = invoiceSource && invoiceSource.uri ?
      <TouchableOpacity style={enterpriseStyles.attachment} onPress={() => {
        attachmentObj.type = 'invoice';
        modalPicDelCfg.visible = true;
        modalPicDelCfg.delTextHide = false; //隐藏删除
        modalPicDelCfg.uri = invoiceSource.uri;
        this.setState({
          previewModalVisible: true
        });
      }} activeOpacity={0.5} >
        <Image source={invoiceSource} style={enterpriseStyles.cover} />
      </TouchableOpacity>
      : <View style={{ flexDirection: 'row' }}>
        <TouchableOpacity style={enterpriseStyles.attachment} onPress={() => {
          this.selectPhotoTapped('invoice', this.invoiceHandle, 'INVOICE');
        }} activeOpacity={0.5} >
          <Image source={uploadPic} style={enterpriseStyles.cover} />
        </TouchableOpacity>
      </View>;
    //发票文字
    const invoiceRowView = (openAcctNo && openAcctNo.length) ?
      <TouchableOpacity activeOpacity={.5} style={enterpriseStyles.optionView} onPress={() => {
        const { navigate } = this.props.navigation;
        navigate('InvoiceEditPage', {
          vo: invoice,
          creditCode: this.creditCode,
          bankLabel
        });
      }}>
        <Text style={enterpriseStyles.text}>{text}</Text>
        <Image source={arrowLeft} style={enterpriseStyles.arrowLeft} />
      </TouchableOpacity>
      : <TouchableOpacity key={0} activeOpacity={.5} style={enterpriseStyles.optionView} onPress={() => {
        const { navigate } = this.props.navigation;
        navigate('InvoiceEditPage', {
          vo: {
            index: 0,
            invoiceAddress: this.sendData.companyInfoVO.invoiceAddress,
          },
          creditCode: this.creditCode,
          bankLabel
        });
      }}>
        <Text style={enterpriseStyles.text}>请选择</Text>
        <Image source={arrowLeft} style={enterpriseStyles.arrowLeft} />
      </TouchableOpacity>;

    return (
      <View style={{ width: 345 * scale }}>
        <View style={enterpriseStyles.attachmentRow}>
          {uploadCell}
          {
            demoSource ?
              <TouchableOpacity style={enterpriseStyles.attachment} onPress={() => {
                if (imgDemo) {
                  // attachmentObj.type = 'invoice';
                  modalPicDelCfg.visible = true;
                  modalPicDelCfg.delTextHide = true; //隐藏删除
                  modalPicDelCfg.uri = imgDemo;
                  this.setState({
                    previewModalVisible: true
                  });
                }
              }} activeOpacity={0.5} >
                <Image source={demoSource} style={enterpriseStyles.cover} />
                <View style={enterpriseStyles.imgDemoBg} >
                  <Text style={enterpriseStyles.imgDemoText}>示例图片</Text>
                </View>
              </TouchableOpacity>
              : null
          }
        </View>

        <View style={enterpriseStyles.field}>
          <Text style={enterpriseStyles.lableText}>
            开票信息({bankLabel})</Text>
          {invoiceRowView}
        </View>

      </View>
    )
  }

  _keyboardDidShow () {
    this.setState({
      keyboard: true,
    });
  }

  _keyboardDidHide () {
    this.setState({
      keyboard: false,
    });
  }

  componentWillUnmount () {
    try {
      this.keyboardDidShowListener.remove();
      this.keyboardDidHideListener.remove();
      this.setState({
        loaded: false
      });
    } catch (error) {
      console.log(error);
    }
  }

  async _didPressNextBtn () {
    const { contactObjList, reference, invoice, addressList, bankList } = this.state;
    const { taxCode, openBankName, openAcctNo, invoicePhoneNo, invoiceAddress } = invoice;
    const { productText } = this.props.navigation.state.params;
    if (contactObjList && contactObjList[0] && contactObjList[0].contactorName && contactObjList[0].contactorName.length) {
      this.sendData.companyInfoVO.linkBy = contactObjList[0].contactorName;
      this.sendData.companyInfoVO.linkPhone = contactObjList[0].mobileNo;
    } else {
      Alert.alert('请填写联系人');
      return;
    }
    if (this.sendData.companyInfoVO.countryCode === '86') {
      if (ValidateDataUtil.isEmpty(this.sendData.companyInfoVO.invoiceFileId)) {
        Alert.alert('请上传开票图片');
        return;
      }
    }
    if (this.sendData.companyInfoVO.countryCode === '86') {
      if (taxCode && openBankName && openAcctNo && invoicePhoneNo && invoiceAddress) {
        this.sendData.companyInfoVO.openBankName = openBankName;
        this.sendData.companyInfoVO.openAcctNo = openAcctNo;
        this.sendData.companyInfoVO.taxCode = taxCode;
        this.sendData.companyInfoVO.invoicePhoneNo = invoicePhoneNo;
        this.sendData.companyInfoVO.invoiceAddress = invoiceAddress;
      } else {
        Alert.alert('请填写完整的开票信息');
        return;
      }
    }
    if (this.invoiceAddrIfRequired && this.invoiceAddrIfRequired.length > 0) {
      if (ValidateDataUtil.isEmpty(this.sendData.companyInfoVO.recvInvoiceAddress)) {
        Alert.alert('请填写发票邮寄地址');
        return;
      }
    }
    if (this.bankIfRequired && this.bankIfRequired.length > 0) {
      if (bankList && bankList.length > 0) {
        this.sendData.acctList = bankList;
      } else {
        Alert.alert('请填写结算银行信息');
        return;
      }
    }
    this.sendData.contactorList = contactObjList.map((item) => {
      item.companyId = this.companyId;
      return item;
    });

    this.sendData.addressList = addressList;
    this.sendData.corpId = this.choice.corpId;
    if (this.requesting) return;
    this.setState({ loaded: true });
    this.requesting = true;
    const responseData = await HTTP.POST(API_GENERATE(API.ADD_APPLY_COMPANY), this.sendData);

    this.setState({
      loaded: false
    })

    if (responseData) {
      const { navigate } = this.props.navigation;
      let newArr = [];
      let newArrAcc = [];
      if (responseData.addressList && responseData.addressList.length) {
        for (let i = 0; i < responseData.addressList.length; i++) {
          newArr[i] = responseData.addressList[i];
          newArr[i].areaText = this.sendData.addressList[i].areaText;
          newArr[i].checked = this.sendData.addressList[i].checked;
        }
        responseData.addressList = responseData.addressList;
      }

      if (responseData.acctList && responseData.acctList.length) {
        for (let i = 0; i < responseData.acctList.length; i++) {
          newArrAcc[i] = responseData.acctList[i];
          newArrAcc[i].checked = this.sendData.acctList[i].checked;
        }
        responseData.addressList = newArr;
        responseData.acctList = newArrAcc;
      }
      this.requesting = false;
      navigate('EnterpriseCreateQualificationInfo', {
        productText: productText,
        requireQualification: this.requireQualification,
        responseData,
        choice: this.choice
      });
    } else {
      this.requesting = false;
    }
  }

  /**
  * 上传图片
  * @param {String} attachment 统一社会信用证文件 分类
  * @param {function} handle
  * @param {String} ocrType 分类
  */
  selectPhotoTapped (attachment, handle, ocrType) {
    const options = {
      title: '请选择图片来源',
      cancelButtonTitle: '取消',
      takePhotoButtonTitle: '拍照',
      chooseFromLibraryButtonTitle: '相册图片',
      quality: 1,
      maxWidth: 1080,
      maxHeight: 1080,
      storageOptions: {
        skipBackup: true,
        // path: 'images'
      },
      mediaType: 'photo',
    };
    ImagePicker.showImagePicker(options, async (response) => {
      if (response.didCancel) {
        return;
      }
      else if (response.error) {
        return;
      }
      else if (response.customButton) {
        return;
      }

      const uploadImgObj = {
        imgUrl: { uri: response.uri },
        url: API_GENERATE(API.IMG_UPLOAD),
      }
      if (ocrType && ocrType.length) {
        uploadImgObj.ocrType = ocrType;
        uploadImgObj.isOcr = 1;
      } else {
        uploadImgObj.isOcr = 0
      }
      this.setState({
        loaded: true
      });
      let responseData = await Upload.uploadImg(uploadImgObj);
      if (responseData) {
        if (attachment == 'invoice') {
          this.setState({
            invoiceSource: { uri: response.uri },
          });
        }
        if (responseData.fileId && handle && (typeof (handle) == 'function')) {
          handle(responseData);
        }
      }
      this.setState({
        loaded: false
      });

    });
  }

  /**
  * 
  * @param {object} data 
  */
  invoiceHandle (data) {
    const { fileId, applyCompanyInvoiceVO } = data;
    this.sendData.companyInfoVO.invoiceFileId = fileId || '';
    const { invoice } = this.state;
    if (applyCompanyInvoiceVO) {
      let { taxCode, openBankName, openAcctNo, invoicePhoneNo, invoiceAddress } = invoice;
      if (!taxCode || taxCode.length) {
        taxCode = applyCompanyInvoiceVO.taxCode;
      }
      if (!openBankName || openBankName.length) {
        openBankName = applyCompanyInvoiceVO.openBankName;
      }
      if (!openAcctNo || openAcctNo.length) {
        openAcctNo = applyCompanyInvoiceVO.openAcctNo;
      }
      if (!invoicePhoneNo || invoicePhoneNo.length) {
        invoicePhoneNo = applyCompanyInvoiceVO.invoicePhoneNo;
      }
      if (!invoiceAddress || invoiceAddress.length) {
        invoiceAddress = applyCompanyInvoiceVO.invoiceAddress;
      }
      this.setState({
        invoice: { taxCode, openBankName, openAcctNo, invoicePhoneNo, invoiceAddress }
      });
    }
    if (!fileId) {
      ToastUtil.showInfo('上传失败，请稍后再试');
      return;
    }
  }

}

const styles = StyleSheet.create({
  ocrWrap: {
    width: 375 * scale,
    height: GLOBAL.SCREEN_HEIGHT,
    backgroundColor: 'rgba(0, 0, 0, 0)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  loadedCell: {
    width: 75 * scale,
    height: 75 * scale,
    backgroundColor: 'rgba(0, 0, 0, .5)',
    borderRadius: 7,
    justifyContent: 'center',
    alignItems: 'center',
  },
  scrollView: {
    flex: 1,
    backgroundColor: '#fff',
  },
  container: {
    flex: 1,
    alignItems: 'center',
  },
  wrap: {
    width: 345 * scale,
  },
  closeTextCell: {
    position: 'absolute',
    left: 8,
    top: 0,
  },
})